<template>
  <!-- 定价方法匹配规则新增、编辑 -->
  <div class="ruleTemplate-data">
    <el-form
      :model="saveForm"
      ref="saveOrEditRef"
      label-width="110px"
      label-position="left"
      :rules="saveFormRules"
    >
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="模板编号：" prop="templateCode">
            <el-input
              v-model="saveForm.templateCode"
              maxlength="40"
              :disabled="operateType==2"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>（只能输入字母、数字及下划线，最长字符数为40位）</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="模板名称：" prop="templateName">
            <el-input
              v-model="saveForm.templateName"
              maxlength="100"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>（只能输入汉字、字母、数字及下划线，最长字符数100）</el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row class="container">
      <el-col style="margin-right:10px;" class="content-left">
        <upper-template :searchIcon="false" :configIcon="false">
           <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="addOrEditModelFunc('1')">新增</el-button>
            <el-button @click="addOrEditModelFunc('2')">编辑</el-button>
            <el-button @click="delModelFunc()">删除</el-button>
          </template>
        </upper-template>
        <el-table
          ref="multipleModelTable"
          :data="tableModelData"
          style="width: 100%"
          @row-click="authorizeModelFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="elementFieldName"
            label="业务元素"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="caliberFlag"
            label="是否使用口径"
            :show-overflow-tooltip="true"
            :formatter="row => (row.caliberFlag == 1 ? '是' : '否')"
          ></el-table-column>
          <el-table-column
            prop="caliberGroupCode"
            label="口径组"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="fieldNum"
            label="顺序号"
            :show-overflow-tooltip="true"
          ></el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog
      v-dialogDrag
      :title="titleModelName"
      :visible.sync="ruleTemplateFieldDi"
      :append-to-body="true"
      width="30%"
      height="500"
      top="2%"
    >
      <div style="height:200px">
      <el-form
        :model="saveFieldForm"
        ref="saveOrEditFieldRef"
        label-width="110px"
        label-position="left"
        :rules="saveFieldFormRules"
      >
        <el-row>
          <el-col :span="18" :offset="3">
            <el-form-item label="业务元素：" prop="elementField">
               <table-select 
               ref="fieldSelect"
               :data="tableElementFieldDataBasic"
               v-model="saveFieldForm.elementField"
               fieldCode='elementField'
               fieldName='elementName'
               :tableHead ="[{prop:'elementField',label:'元素字段'},{prop:'elementName',label:'元素名称'},]"
               @change="selectCaliberGroup()"
               ></table-select>
            </el-form-item>
          </el-col>
          <el-col :span="18" :offset="3">
            <el-form-item label="是否使用口径：" prop="caliberFlag">
              <el-select v-model="saveFieldForm.caliberFlag" placeholder="请选择" style="width:100%" @change="caliberFlagChange">
                <el-option
                  v-for="item in caliberFlags"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18" :offset="3" v-if="caliberGroupDi">
            <el-form-item label="口径方案：" prop="caliberGroupCode" >
               <table-select 
               ref="caliberSelect"
               :data="tableCaliberGroupDataBasic"
               v-model.trim="saveFieldForm.caliberGroupCode"
               fieldCode='caliberProjectCode'
               fieldName='caliberProjectName'
               :tableHead ="[{prop:'caliberProjectCode',label:'口径编码'},{prop:'caliberProjectName',label:'口径名称'},]"
               ></table-select>
            </el-form-item>
          </el-col>
          <el-col :span="18" :offset="3">
            <el-form-item label="顺序号：" prop="fieldNum">
              <el-input
                v-model.trim="saveFieldForm.fieldNum"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      </div>
      <div slot="footer">
        <el-button @click="saveFieldFun">确 定</el-button>
        <el-button @click="ruleTemplateFieldDi = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ruleTemplate } from "@/api/index";
import tableSelect from "@/components/ftp/tableSelect";
import { getDict } from "@/api/getDict";
export default {
  data() {
    return {
      //保存实体
      saveForm: {
        templateType: this.templateType,
        templateName: "",
        templateCode: ""
      },
      //规则字段实体
      saveFieldForm: {
        caliberFlag: "0",
        elementField:"",
        fieldNum:"",
        caliberGroupCode:"",
      },
      //表单字段规则校验
      saveFormRules: {
        templateCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_]{1,40}$/,
            message: "只可输入(1-40)位的英文字母、数字和下划线！",
            trigger: "blur"
          },
          { validator: this.templateCodeValid, trigger: "blur" }
        ],
        templateName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]{1,100}$/,
            message: "只可输入1-100位英文数字汉字和_",
            trigger: "blur"
          },
          { validator: this.templateNameValid, trigger: "blur" }
        ]
      },
      saveFieldFormRules: {
        elementField: [
          { required: true, message: "该输入项为必输项", trigger: "change" },
          { validator: this.elementFieldValid, trigger: "change" }
        ],
        caliberFlag: [
          { required: true, message: "该输入项为必输项", trigger: "change" }
        ],
        caliberGroupCode: [
          { required: true, message: "该输入项为必输项", trigger: "change" }
        ],
        fieldNum: [
          { required: true, message: "该输入项为必输项", trigger: "change" },
          {
            pattern: /^[0-9]{1,9}$/,
            message: "最多只可输入9位数字！",
            trigger: "blur"
          },
          { validator: this.fieldNumValid, trigger: "blur" }
        ]
      },
      //列表数据
      tableModelData: [],
      //是否使用口径字典
      caliberFlags: [],
      //定价方法规则字段弹窗标识
      ruleTemplateFieldDi: false,
      titleModelName: "",
      //业务元素悬浮框
      elementFieldContent : false,
      //业务元素列表初始
      tableElementFieldDataBasic: [],
      //业务元素列表
      tableElementFieldData: [],
      //口径方案悬浮框
      caliberGroupContent : false,
      //口径方案初始列表
      tableCaliberGroupDataBasic: [],
      //口径方案列表
      tableCaliberGroupData: [],
      //口径方案标识
      caliberGroupDi: false,
      //模板字段操作状态
      fieldOperateType: 1,
      //编辑业务元素
      elementFieldOld: "",
      //编辑顺序号
      fieldNumOld: "",
      //编辑的模板元素
      savaFieldFormOld: {},
      //编辑模板名称
      templateNameOld: "",
      elementField:"",
      elementName:""
    };
  },
  props: {
    templateId: {
      type: String,
      default: ""
    },
    operateType: {
      type: String,
      default: ""
    },
    templateType: {
      type: String,
      default: ""
    },
    templateCode: {
      type: String,
      default: ""
    },
    templateName: {
      type: String,
      default: ""
    },
    templateTitle:{
      type: String,
      default: ""
    }
  },
  watch: {
   

  },
  components: {
    tableSelect
  },
  created() {
    this.getDict();
    this.elementFieldDataSelect();
  },
  computed: {
    
  },
  mounted() {
    //this.searchModelFunc();
  },
  inject:['closeRuleTemplateDi'],
  methods: {
    //顺序号验证
    fieldNumValid(rule, value, callback){
      let index = 0;
      this.tableModelData.forEach(item=>{
        if(value == item.fieldNum) {
          if(this.fieldOperateType == "1") {
            index = 1;
            callback(new Error("此顺序号已存在，无法使用！"));
          } else {
            if (this.fieldNumOld != value) {
              index = 1;
              callback(new Error("此顺序号已存在，无法使用！"));
            }
          }
        }
      });
      if(index == 0) {
        callback();
      }
    },
    //业务元素验证
    elementFieldValid(rule, value, callback){
      let index = 0;
      this.tableModelData.forEach(item=>{
        if(value === item.elementField) {
          if(this.fieldOperateType == "1") {
            index = 1;
            callback(new Error("此业务元素已存在，无法使用！"));
          } else {
            if (this.elementFieldOld != value) {
              index = 1;
              callback(new Error("此业务元素已存在，无法使用！"));
            }
          }
        }
      });
      if(index == 0) {
        callback();
      }
    },
    //模板编号验证
    templateCodeValid(rule, value, callback){
      if(this.operateType == "1") {
        let data = {
          templateCode: value,
          templateType: this.templateType
        };
        ruleTemplate.checkUsing(data).then(res => {
          if (res.code === 200) {
            if(res.data != "false") {
              callback(new Error("此模板编号已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      } else {
        callback();
      }
    },
    //模板名称验证
    templateNameValid(rule, value, callback){
      if(this.operateType == "1"||(this.operateType == "2"&&this.templateNameOld != value)) {
        let data = {
          templateName: value,
          templateType: this.templateType
        };
        ruleTemplate.checkUsing(data).then(res => {
          if (res.code === 200) {
            if(res.data != "false") {
              callback(new Error("此模板名称已存在，无法使用！"));
            } else {
              callback();
            }
          }
        });
      } else {
        callback();
      }
    },
    //保存规则模板
    saveRuleTemplate() {
      this.$refs["saveOrEditRef"].validate(valid => {
        if(valid) {
          let length = this.tableModelData.length;
          if(length == 0) {
            this.$message.warning("请新增规则字段信息");
            return false;
          } else {
            this.saveForm.ruleTemplateFields = this.tableModelData;
            let data = {
              operateType: this.operateType,
              ruleTemplate: {...this.saveForm}
            };
            ruleTemplate.save(data).then(res => {
              if (res.code == 200) {
                this.$message.success("保存成功");
                this.$emit("backReSearch");
                this.closeRuleTemplateDi();
                return true;
              } else {
                this.$message.error(res.message || "保存失败");
                return false;
              }
            });
          }
        }
      });
    },
    //是否使用口径选择
    caliberFlagChange(val) {
      if(val === "1") {
        //使用口径，显示口径方案选择
        this.caliberGroupDi = true;
      } else {
        this.caliberGroupDi = false;
      }
    },
    //业务元素实时检索
    searchElementField() {
      let search = this.saveFieldForm.elementFieldName;
      this.tableElementFieldData = [];
      this.tableElementFieldDataBasic.filter(item=>{
        if(item.elementName.indexOf(search) != -1||item.elementField.indexOf(search) != -1) {
          this.tableElementFieldData.push(item);
        }
      });
      
      if(!this.elementFieldContent) {
        this.elementFieldContent = true;
      }
    },
   
    elementFieldDataSelect () {
      let data = {
        pricingFlag: 1,
        nopage: true
      }
      ruleTemplate.findBusinessByType(data).then(res => {
        if (res.code === 200) {
          this.tableElementFieldDataBasic = res.rows;
        }
      });
    },
    authorizeElementFieldFor(row){
      this.saveFieldForm.elementField = row.elementField;
      this.saveFieldForm.elementFieldName = row.elementName;
      this.elementFieldContent = false;
    },
    searchCaliberGroup() {
      let search = this.saveFieldForm.caliberGroupCode;
      this.tableCaliberGroupData = [];
      this.tableCaliberGroupDataBasic.filter(item=>{
        if(item.caliberProjectName.indexOf(search) != -1||item.caliberProjectCode.indexOf(search) != -1) {
          this.tableCaliberGroupData.push(item);
        }
      });
      if(!this.elementFieldContent) {
        this.elementFieldContent = true;
      }
    },
    //口径方案选择
    selectCaliberGroup () {
      if (this.saveFieldForm.elementField != null&&this.saveFieldForm.elementField != '') {
        let data = {
          templateFieldId: this.saveFieldForm.elementField
        }
        ruleTemplate.findCaliberByTemplateFieldId(data).then(res => {
          if (res.code === 200) {
            this.tableCaliberGroupDataBasic = res.datas;
          }
        });
      } else {
        this.tableCaliberGroupDataBasic = [];
      }
      this.saveFieldForm.caliberGroupCode='';
      this.saveFieldForm.caliberFlag='0';
      this.caliberFlagChange('0')
    },
    authorizeCaliberGroupFor(row){
      this.saveFieldForm.caliberGroupCode = row.caliberProjectCode;
      this.caliberGroupContent = false;
    },
    //查询
    searchModelFunc() {
      if(this.$refs.saveOrEditRef) {
        this.$refs.saveOrEditRef.resetFields();
      }
      if(this.templateId != null&&this.templateId != "") {
        this.saveForm.templateCode = this.templateCode;
        this.saveForm.templateName = this.templateName;
        if(this.operateType == "2") {
          this.templateNameOld = this.templateName;
        }
        this.saveForm.templateId = this.templateId;
        let data = {templateId:this.templateId};
        ruleTemplate.findAllRuleTemplateField(data).then(res => {
          if (res.code === 200) {
            this.tableModelData = res.datas;
          }
        });
      } else {
        this.saveForm.templateType = this.templateType;
        this.saveForm.templateName = "";
        this.saveForm.templateCode = "";
        this.tableModelData = [];
      }
    },
    //字典信息
    getDict() {
      getDict("ftp_boolean_bork").then(res => {
        if (res.code == 200) {
          this.caliberFlags = res.datas;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //新增、编辑规则字段
    addOrEditModelFunc(val) {
      this.fieldOperateType = val;
      if(this.$refs.saveOrEditFieldRef) {
        this.$refs.saveOrEditFieldRef.resetFields();
      }
      if(val === "1") {
        this.titleModelName = "添加"+this.templateTitle+"规则字段信息";//"添加定价曲线规则字段信息"
        this.caliberGroupDi = false;
        this.saveFieldForm.caliberFlag= '0';  
        this.saveFieldForm.elementField= "";
        this.saveFieldForm.caliberGroupCode= "";
        this.saveFieldForm.caliberGroupName= "";
        this.saveFieldForm.elementFieldName= "";
        this.saveFieldForm.fieldNum= ""
        this.ruleTemplateFieldDi = true;

      } else if(val === "2") {
        this.titleModelName = "编辑"+this.templateTitle+"规则字段信息";//"编辑定价曲线规则字段信息";
        let selection = this.$refs.multipleModelTable.selection; 
        if(selection.length!=1){return this.$message.warning('请勾选<一条>要编辑的数据')} 
        this.saveFieldForm = {...selection[0]};
        this.savaFieldFormOld = selection[0];
        this.elementFieldOld = selection[0].elementField;
        this.fieldNumOld = selection[0].fieldNum;
        this.ruleTemplateFieldDi = true;
        if(selection[0].caliberFlag==0) {
          this.caliberGroupDi = false;
        } else {
          this.caliberGroupDi = true;
        }
      }
      
    },
    //保存规则字段
    saveFieldFun () {
      this.$refs["saveOrEditFieldRef"].validate(valid => {
        if (valid) {
          this.saveFieldForm.elementFieldName=this.$refs.fieldSelect.name;
          this.saveFieldForm.caliberGroupName=this.$refs.caliberSelect?this.$refs.caliberSelect.name:"";
          let data = {...this.saveFieldForm};
          if(this.fieldOperateType === "1") {
            this.tableModelData.push(data);
          } else {
            this.tableModelData.splice(this.tableModelData.indexOf(this.savaFieldFormOld),1,data);
          }
          this.ruleTemplateFieldDi = false;
          this.$forceUpdate()
        } 
      });
    },
    //删除规则字段
    delModelFunc() {
      let selection = this.$refs.multipleModelTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的规则模板字段数据");
      }
      this.$confirm("您确定要删除选中规则模板字段吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
         selection.forEach(item=>{
              this.tableModelData.splice(this.tableModelData.indexOf(item),1);
         });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //点击行选中
    authorizeModelFor(row) {
      if (this.$refs.multipleModelTable) {
          this.$refs.multipleModelTable.clearSelection()
      }
      this.$refs.multipleModelTable.toggleRowSelection(row, true)
    }
  }
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
</style>